<script setup>
import { ref, onMounted } from 'vue'
import axios from '../utils/request'
import baseURL from '../config/baseURL'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格数据获取逻辑
const categories = ref([])
const loading = ref(false)

const addDialogVisible = ref(false)
const addCategoryName = ref('')

const editDialogVisible = ref(false)
const editForm = ref({
    id: null,
    name: '',
    status: 0
})

const fetchCategories = async () => {
    loading.value = true
    try {
        const res = await axios.get('/api/category/list')
        if (res.data.code === 1) {
            categories.value = res.data.data
        } else {
            ElMessage.error(res.data.message || '获取分类失败')
        }
    } catch (e) {
        ElMessage.error('获取分类失败')
    } finally {
        loading.value = false
    }
}

/*
  新增分类按钮点击逻辑
*/
const onAdd = () => {
    addCategoryName.value = ''
    addDialogVisible.value = true
}

// 提交新增
const submitAddCategory = async () => {
    if (!addCategoryName.value.trim()) {
        ElMessage.warning('请输入分类名称')
        return
    }
    try {
        const res = await axios.get('/api/category/add', {
            params: { name: addCategoryName.value }
        })
        if (res.data.code === 1) {
            ElMessage.success('添加成功')
            addDialogVisible.value = false
            fetchCategories()
        } else {
            ElMessage.error(res.data.message || '添加失败')
        }
    } catch (e) {
        ElMessage.error('添加失败')
    }
}

/**
 * 修改按钮点击逻辑
*/
const onEdit = (row) => {
    editForm.value = { ...row }
    // 确保 name/status 字段存在
    if (editForm.value.name === undefined) editForm.value.name = ''
    if (editForm.value.status === undefined) editForm.value.status = 0
    editDialogVisible.value = true
}

// 提交修改
const submitEditCategory = async () => {
    if (!editForm.value.name.trim()) {
        ElMessage.warning('请输入分类名称')
        return
    }
    try {
        const res = await axios.post('/api/category/update', {
            id: editForm.value.id,
            name: editForm.value.name,
            status: editForm.value.status
        })
        if (res.data.code === 1) {
            ElMessage.success('修改成功')
            editDialogVisible.value = false
            fetchCategories()
        } else {
            ElMessage.error(res.data.message || '修改失败')
        }
    } catch (e) {
        ElMessage.error('修改失败')
    }
}

/*
  删除按钮点击逻辑
*/
const onDelete = (row) => {
    ElMessageBox.confirm(
        `确定要删除分类"${row.name}"吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        try {
            const res = await axios.delete(`/api/category/delete/${row.id}`)
            if (res.data.code === 1) {
                ElMessage.success('删除成功')
                fetchCategories()
            } else {
                ElMessage.error(res.data.message || '删除失败')
            }
        } catch (e) {
            ElMessage.error('删除失败')
        }
    }).catch(() => {
        // 用户取消
    })
}

onMounted(fetchCategories)
</script>

<template>
    <div class="category-management">
        <h1>菜品分类管理</h1>
        <div class="content">
            <div style="display: flex; justify-content: flex-end; margin-bottom: 10px;">
                <el-button type="primary" @click="onAdd">新增分类</el-button>
            </div>
            <!-- 表格内容 -->
            <el-table :data="categories" v-loading="loading" style="width: 100%">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="name" label="分类名称" width="150" />
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                            {{ scope.row.status === 1 ? '启售' : '停售' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="150" />
                <el-table-column prop="updateTime" label="更新时间" width="150" />
                <el-table-column label="操作" width="180">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="onEdit(scope.row)">修改</el-button>
                        <el-button type="danger" size="small" @click="onDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- ✅ 新增分类弹窗 -->
            <el-dialog v-if="addDialogVisible" v-model="addDialogVisible" title="新增分类" width="400px">
                <el-input v-model="addCategoryName" placeholder="请输入分类名称" maxlength="20" show-word-limit
                    @keyup.enter="submitAddCategory" />
                <template #footer>
                    <el-button @click="addDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitAddCategory">确定</el-button>
                </template>
            </el-dialog>

            <!-- ✅ 修改分类弹窗 -->
            <el-dialog v-if="editDialogVisible" v-model="editDialogVisible" title="修改分类" width="400px">
                <el-form :model="editForm" label-width="80px">
                    <el-form-item label="分类名称">
                        <el-input v-model="editForm.name" maxlength="20" show-word-limit />
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-radio-group v-model="editForm.status">
                            <el-radio :label="1">启售</el-radio>
                            <el-radio :label="0">停售</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <el-button @click="editDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitEditCategory">确定</el-button>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<style scoped>
.category-management {
    width: 100%;
    padding: 20px;
}

.content {
    width: 100%;
    background-color: white;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}
</style>